<?php

/*
The MIT License

Copyright (c) 2008 T.J. Leahy Jr.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

//a singleton to create a JSON response.  JSON will be output automatically
class JSON
{
    public static $response;
    
    private static $instance;
    
    protected static $dump;
      
    //turns $response into an object w/arrays
    private function __construct() {
        self::$response = new stdClass();
        self::$dump = true;
    }
    
    //dumps the JSON automatically
    public function __destruct() {
        if (self::$dump) {
            $json = json_encode(self::$response);
            
            if (!headers_sent()){
                header("Content-Type: application/json");
                header("Content-Length: ". strlen($json));
            }
            print $json;
        }
        
    }
              
    //create self (if needed) and return instance of self
    //can pass unlimited arguments (strings only) and they will be JSON parents
    public static function getInstance() {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
            
            if (func_num_args() > 0) {
                $args = func_get_args();   
                foreach($args as $key) {
                    self::addKey($key);
                }
            } 
        }
        return self::$instance;
    }
    
    //cancel outputting JSON
    public static function cancel() {
        self::$dump = false;
    }
    
    public static function restart($clearresponse = false) {
        self::$dump = true;
        if ($clearresponse) {
            unset(self::$response);
            self::$response;
        }
    }
    
    
    
    //safely add a JSON parent (each argument becomes a key)
    public static function addKey() {
        $args = func_get_args();
        foreach($args as $key) {
            self::$response->{$key} = (isset(self::$response->{$key})) ? self::$response->{$key} : array();
        }
    }
  
  
    //removes the JSON parent and all its properties (all arguments become a key)
    public static function removeKey() {
        $args = func_get_args();
        foreach($args as $key) {
            unset(self::$response->{$key});
        }
        
    }
  
  
    //add a top level JSON key and a predefined value for it
    public static function addKeyVal($key, $val) {
        self::$response->{$key} = $val;
    }
    

    
    
    //pushes a PHP object onto a JSON parent
    public static function addTo($key, $obj) {
        self::addKey($key);
        array_push(self::$response->{$key}, $obj);
    }
    
    
    //add an associative array directly to a JSON parent
    public static function addArrayTo($key, $arr) {
        $obj = self::array2object($arr);
        self::addTo($key, $obj);
    }
    
        //convert an associative array to an object
    public static function array2object($arr) {
        $obj = new stdClass();
        foreach ($arr as $key => $value) {
            $obj->{$key} = $value;
        }
        return $obj;
    }

}


//non native json_encode function for PHP < 5.2 w/o the php-json extension
//taken from "Steve" http://us2.php.net/manual/en/function.json-encode.php#82904
if (!function_exists('json_encode'))
{
  function json_encode($a=false)
  {
    if (is_null($a)) return 'null';
    if ($a === false) return 'false';
    if ($a === true) return 'true';
    if (is_scalar($a))
    {
      if (is_float($a))
      {
        // Always use "." for floats.
        return floatval(str_replace(",", ".", strval($a)));
      }

      if (is_string($a))
      {
        static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
        return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
      }
      else
        return $a;
    }
    $isList = true;
    for ($i = 0, reset($a); $i < count($a); $i++, next($a))
    {
      if (key($a) !== $i)
      {
        $isList = false;
        break;
      }
    }
    $result = array();
    if ($isList)
    {
      foreach ($a as $v) $result[] = json_encode($v);
      return '[' . join(',', $result) . ']';
    }
    else
    {
      foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
      return '{' . join(',', $result) . '}';
    }
  }
}




?>
